package cn.baddonkey;

import cn.baddonkey.util.TransApi;
import cn.baddonkey.util.TransResult;
import com.google.gson.Gson;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;

/**
 * @author junheng.zhou
 * @date 2022-11-01 13:54
 **/
public class DocHelper extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent event) {
        Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
        Project project = event.getRequiredData(CommonDataKeys.PROJECT);
        Document document = editor.getDocument();

        Caret currentCaret = editor.getCaretModel().getCurrentCaret();

        SelectionModel model = editor.getSelectionModel();

        String selectedText = model.getSelectedText();

        TransApi api = new TransApi();
        String transResultJSON = null;
        try {
            transResultJSON = api.getTransResult(selectedText, "en", "zh");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Gson gson = new Gson();
        TransResult transResult = gson.fromJson(transResultJSON, TransResult.class);
        String dst = transResult.getTrans_result().get(0).getDst().replace("_", "");
        int lineStartOffset = document.getLineStartOffset(currentCaret.getLogicalPosition().line);
        int lineEndOffset = document.getLineEndOffset(currentCaret.getLogicalPosition().line);

        String text = document.getText(new TextRange(lineStartOffset, lineEndOffset));

        StringBuilder preStr = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            if (' ' == text.charAt(i) || '\t' == text.charAt(i)) {
                preStr.append(text.charAt(i));
            } else {
                break;
            }
        }

        String s = text.replaceAll("^[ \t]+", "");
        int offset = text.length() - s.length();
        int start = lineStartOffset + offset;

        StringBuilder blankStr = new StringBuilder();
        for (int i = 0; i < offset; i++) {
            blankStr.append(" ");
        }

        StringBuilder builder = new StringBuilder();
        builder.append("/**")
                .append("\n")
                .append(preStr)
                .append("* ")
                .append(dst)
                .append("\n")
                .append(preStr)
                .append("*/\n")
                .append(preStr);

        WriteCommandAction.runWriteCommandAction(project, new Runnable() {
            @Override
            public void run() {
                document.insertString(start, builder.toString());
//                editor.getCaretModel().moveToOffset(currentOffSet + varName.length());
            }
        });

    }
}
